import React, { useState } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  Image,
  ActivityIndicator,
} from 'react-native';
import {
  Button,
  Card,
  Title,
  Paragraph,
  FAB,
  Portal,
  Dialog,
  TextInput,
  Switch,
  Text,
} from 'react-native-paper';
import * as ImagePicker from 'expo-image-picker';
import Toast from 'react-native-toast-message';

import { ColorizeService, ColorizeParams } from '../services/api';
import { useColorizeStore } from '../store/colorizeStore';

export function HomeScreen({ navigation }: any) {
  const [image, setImage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [settings, setSettings] = useState<ColorizeParams>({
    style: 'anime',
    strength: 0.7,
    guidance_scale: 7.5,
    num_inference_steps: 20,
  });
  const [showSettings, setShowSettings] = useState(false);
  
  const { addTask } = useColorizeStore();

  const pickImage = async () => {
    try {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      
      if (status !== 'granted') {
        Toast.show({
          type: 'error',
          text1: 'Permission needed',
          text2: 'Please grant camera roll permissions',
        });
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 0.8,
      });

      if (!result.canceled) {
        setImage(result.assets[0].uri);
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to pick image',
      });
    }
  };

  const takePhoto = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      
      if (status !== 'granted') {
        Toast.show({
          type: 'error',
          text1: 'Permission needed',
          text2: 'Please grant camera permissions',
        });
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        aspect: [4, 3],
        quality: 0.8,
      });

      if (!result.canceled) {
        setImage(result.assets[0].uri);
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to take photo',
      });
    }
  };

  const handleColorize = async () => {
    if (!image) {
      Toast.show({
        type: 'error',
        text1: 'No image selected',
        text2: 'Please select an image first',
      });
      return;
    }

    setLoading(true);
    try {
      const response = await ColorizeService.colorizeImage(image, settings);
      
      // Add to store
      addTask({
        id: response.task_id,
        originalImage: image,
        status: 'pending',
        params: settings,
        createdAt: new Date().toISOString(),
      });

      // Navigate to result screen
      navigation.navigate('Result', { taskId: response.task_id });
      
      Toast.show({
        type: 'success',
        text1: 'Processing started',
        text2: 'Your image is being colorized',
      });
    } catch (error: any) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: error.message || 'Failed to start colorization',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.content}>
        <Card style={styles.card}>
          <Card.Content>
            <Title>Upload Manga Sketch</Title>
            <Paragraph>
              Select a manga sketch to colorize it with AI
            </Paragraph>
          </Card.Content>
        </Card>

        {image && (
          <Card style={styles.card}>
            <Card.Cover source={{ uri: image }} style={styles.image} />
            <Card.Actions>
              <Button onPress={() => setImage(null)}>Remove</Button>
            </Card.Actions>
          </Card>
        )}

        <View style={styles.buttonContainer}>
          <Button
            mode="contained"
            onPress={pickImage}
            style={styles.button}
            icon="image"
          >
            Choose from Gallery
          </Button>

          <Button
            mode="contained"
            onPress={takePhoto}
            style={styles.button}
            icon="camera"
          >
            Take Photo
          </Button>

          <Button
            mode="contained"
            onPress={() => setShowSettings(true)}
            style={styles.button}
            icon="cog"
          >
            Settings
          </Button>

          {image && (
            <Button
              mode="contained"
              onPress={handleColorize}
              style={styles.button}
              loading={loading}
              disabled={loading}
              icon="palette"
            >
              Colorize
            </Button>
          )}
        </View>
      </View>

      <Portal>
        <Dialog visible={showSettings} onDismiss={() => setShowSettings(false)}>
          <Dialog.Title>Colorization Settings</Dialog.Title>
          <Dialog.Content>
            <Text>Style:</Text>
            <Button
              mode={settings.style === 'anime' ? 'contained' : 'outlined'}
              onPress={() => setSettings({ ...settings, style: 'anime' })}
            >
              Anime
            </Button>
            <Button
              mode={settings.style === 'realistic' ? 'contained' : 'outlined'}
              onPress={() => setSettings({ ...settings, style: 'realistic' })}
            >
              Realistic
            </Button>

            <TextInput
              label="Strength (0.1-1.0)"
              value={settings.strength.toString()}
              onChangeText={(text) => setSettings({ ...settings, strength: parseFloat(text) || 0.7 })}
              keyboardType="numeric"
            />

            <TextInput
              label="Guidance Scale (1.0-20.0)"
              value={settings.guidance_scale.toString()}
              onChangeText={(text) => setSettings({ ...settings, guidance_scale: parseFloat(text) || 7.5 })}
              keyboardType="numeric"
            />
          </Dialog.Content>
          <Dialog.Actions>
            <Button onPress={() => setShowSettings(false)}>Close</Button>
          </Dialog.Actions>
        </Dialog>
      </Portal>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    padding: 16,
  },
  card: {
    marginBottom: 16,
  },
  image: {
    height: 300,
    resizeMode: 'contain',
  },
  buttonContainer: {
    gap: 12,
  },
  button: {
    marginVertical: 4,
  },
});
